package com.example.crop_image_project;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;

/**
 * @author Elvis
 * @version v1.0
 * @since 2024/9/4.
 */
//图片灰度化
public class BitmapUtil {

    public static Bitmap decodeResource(Context context, int mipMapRes) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), mipMapRes, null);
        return bitmap;
    }

    public static Bitmap bitmap2Gray(Bitmap bmSrc) {
        // 得到图片的长和宽
        int width = bmSrc.getWidth();
        int height = bmSrc.getHeight();
        // 创建目标灰度图像
        Bitmap bmpGray = null;
        bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        // 创建画布
        Canvas c = new Canvas(bmpGray);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmSrc, 0, 0, paint);
        return bmpGray;
    }

    /**
     * 根据遮罩层剪切原图
     *
     * @param originalBitmap
     * @param maskBitmap
     * @return
     */
    public static Bitmap cropContour( Bitmap originalBitmap, Bitmap maskBitmap) {
        int width = originalBitmap.getWidth();
        int height = originalBitmap.getHeight();
        int[] maskPixels = new int[width * height];
        maskBitmap.getPixels(maskPixels, 0, maskBitmap.getWidth(), 0, 0, width, height);
        Bitmap resultBitmap = Bitmap.createBitmap(width, height, originalBitmap.getConfig());

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int maskPixel = maskPixels[y * width + x];
                //半透明的白色也留存
                if (Color.red(maskPixel) == Color.green(maskPixel) &&
                        Color.green(maskPixel) == Color.blue(maskPixel) &&
                        Color.red(maskPixel) != 0) {
                    int pixelColor = originalBitmap.getPixel(x, y);
                    resultBitmap.setPixel(x, y, pixelColor);
                } else {
                    resultBitmap.setPixel(x, y, Color.TRANSPARENT);
                }
            }
        }

        return resultBitmap;
    }
}





